<template>
  <div class="wapper">
    <div @click="show = true" class="value">{{ valueMirror }}</div>

    <van-popup
      v-model="show"
      safe-area-inset-bottom
      close-on-popstate
      position="bottom"
      get-container="body"
    >
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        :show-toolbar="false"
      />
    </van-popup>
  </div>
</template>

<script>
import { DatetimePicker, Popup } from "vant";
// import dayjs from "dayjs";

export default {
  name: "PickerDate",
  components: {
    [DatetimePicker.name]: DatetimePicker,
    [Popup.name]: Popup,
  },
  model: {
    event: "change",
  },
  props: {
    value: {
      type: [String, Number],
      required: true,
    },
  },
  data() {
    return {
      show: false,
      currentDate: new Date(),
    };
  },
  computed: {
    valueMirror: {
      get: function () {
        return this.value;
      },
      set: function (val) {
        this.$emit("change", val);
      },
    },
  },
  watch: {
    show(val) {
      if (val) {
        this.currentDate = new Date();
      }
    },
    currentDate(val, oldVal) {
      if (val === oldVal) return;
      this.valueMirror = this.formatter(this.currentDate, "yyyy-MM-dd hh:mm:ss");
    },
  },
  methods: {
    formatter(value, fmt) {
      if (!value) {
        return "";
      }
      let date = new Date(value);
      if (date === "Invalid Date") {
        date = new Date(parseFloat(value));
      }
      if (!fmt) {
        fmt = "yyyy-MM-dd hh:mm:ss";
      }
      const o = {
        "M+": date.getMonth() + 1, // 月份
        "d+": date.getDate(), // 日
        "h+": date.getHours(), // 小时    
        "m+": date.getMinutes(), // 分
        "s+": date.getSeconds(), // 秒
        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
        );
      }
      Object.keys(o).forEach((k) => {
        if (new RegExp(`(${k})`).test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
          );
        }
      });
      return fmt;
    },
  },
  created() {
    if (!this.valueMirror)
      this.valueMirror = this.formatter(this.currentDate, "yyyy-MM-dd hh:mm:ss");
  },
};
</script>

<style lang="less" scoped>
.wapper,
.value {
  width: 100%;
  height: 100%;
  text-align: center;
}
/deep/.van-popup--bottom {
  height: 50% !important;
}
</style>